using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace PKGames.MiniGames.VoxelGame.UI.GameUI.Scripts
{
	public class TrialButtonController : MonoBehaviour
	{
		[SerializeField]
		private GameObject _holder;

		[SerializeField]
		private Text _timer;

		[SerializeField]
		private Image _counter;

		[SerializeField]
		private Button _timerButton;

		private float _totalTrialTime;

		private Action _onTimerFinish;

		public void Setup(bool hasTrial, float totalTrialTime, UnityAction onTouch, Action onTimerFinish)
		{
			_holder.gameObject.SetActive(hasTrial);
			if (hasTrial)
			{
				_totalTrialTime = totalTrialTime;
				_timerButton.onClick.AddListener(onTouch);
				_onTimerFinish = onTimerFinish;
				_counter.fillAmount = 1f;
				StartCoroutine(Countdown());
			}
		}

		private IEnumerator Countdown()
		{
			for (float time = 0f; time < _totalTrialTime; time += Time.deltaTime)
			{
				_counter.fillAmount = 1f - time / _totalTrialTime;
				float remainingTime = _totalTrialTime - time;
				_timer.text = Mathf.Floor(remainingTime / 60f).ToString("00") + ":" + (remainingTime % 60f).ToString("00");
				yield return null;
			}
			_counter.fillAmount = 0f;
			_timer.text = "00:00";
			_onTimerFinish.Fire();
		}

		public void StopCountdown()
		{
			StopAllCoroutines();
			_holder.SetActive(value: false);
		}
	}
}
